<template>
  <div class="supplier-product-container">
    <!-- 头部操作栏 -->
    <div class="operation-bar">
      <el-select 
        v-model="currentSupplierId" 
        placeholder="请选择供应商" 
        @change="handleSupplierChange"
        clearable
      >
        <el-option
          v-for="item in supplierOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-input
        v-model="searchForm.productName"
        placeholder="请输入商品名称"
        clearable
        @clear="handleSearch"
        style="width: 200px"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>

      <el-button type="primary" @click="handleAdd" :disabled="!currentSupplierId">
        新增商品
      </el-button>
    </div>

    <!-- 商品列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="productCode" label="商品编码" width="150" />
      <el-table-column prop="productName" label="商品名称" min-width="180" />
      <el-table-column prop="specification" label="规格" width="150" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="price" label="价格" width="120">
        <template slot-scope="scope">
          {{ scope.row.price | currency }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="primary" 
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button 
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="商品编码" prop="productCode">
          <el-input v-model="form.productCode" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" />
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="form.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'SupplierProduct',
  filters: {
    currency(value) {
      return value ? `¥ ${Number(value).toFixed(2)}` : '¥ 0.00'
    }
  },
  data() {
    return {
      // 供应商选择
      currentSupplierId: null,
      supplierOptions: [],
      
      // 表格数据
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 搜索表单
      searchForm: {
        productName: ''
      },
      
      // 新增/编辑对话框
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        supplierId: null,
        productCode: '',
        productName: '',
        specification: '',
        unit: '',
        price: 0,
        remark: '',
      },
      rules: {
        productCode: [
          { required: true, message: '请输入商品编码', trigger: 'blur' },
          { pattern: /^\S+$/, message: '商品编码不能包含空格', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { pattern: /\S/, message: '商品名称不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
        ]
      },
    }
  },
  created() {
    this.fetchSuppliers()
    // 从 URL 获取供应商 ID
    const supplierId = this.$route.query.supplierId
    if (supplierId) {
      this.currentSupplierId = Number(supplierId)
      this.fetchData()
    }
  },
  methods: {
    // 获取供应商列表
    async fetchSuppliers() {
      try {
        const res = await request({
          url: '/supplier/list',
          method: 'get'
        })
        if (res.code === 200) {
          this.supplierOptions = res.data
        }
      } catch (error) {
        this.$message.error('获取供应商列表失败')
      }
    },

    // 获取商品列表
    async fetchData() {
      if (!this.currentSupplierId) return
      try {
        const res = await request({
          url: '/supplier-product/page',
          method: 'get',
          params: {
            supplierId: this.currentSupplierId,
            current: this.currentPage,
            size: this.pageSize,
            productName: this.searchForm.productName
          }
        })
        if (res.code === 200) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      } catch (error) {
        this.$message.error('获取商品列表失败')
      }
    },

    // 供应商变更
    handleSupplierChange() {
      this.currentPage = 1
      this.fetchData()
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增商品'
      this.form = {
        id: null,
        supplierId: this.currentSupplierId,
        productCode: '',
        productName: '',
        specification: '',
        unit: '',
        price: 0,
        remark: '',
      }
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑商品'
      this.form = {
        ...row,
      }
      this.dialogVisible = true
    },

    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该商品?', '提示', {
          type: 'warning'
        })
        const res = await request({
          url: `/supplier-product/${row.id}`,
          method: 'delete'
        })
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const res = await request({
              url: this.form.id ? '/supplier-product/update' : '/supplier-product/add',
              method: this.form.id ? 'put' : 'post',
              data: {
                id: this.form.id,
                supplierId: this.currentSupplierId,
                productCode: this.form.productCode.trim(),
                productName: this.form.productName.trim(),
                specification: this.form.specification?.trim(),
                unit: this.form.unit?.trim(),
                price: this.form.price,
                remark: this.form.remark?.trim(),
              }
            })
            
            if (res.code === 200) {
              this.$message.success(this.form.id ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchData()
            }
          } catch (error) {
            this.$message.error(error.response?.data?.msg || '操作失败')
          }
        }
      })
    },
  }
}
</script>

<style scoped>
.supplier-product-container {
  padding: 20px;
}
.operation-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.el-select {
  width: 200px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 